package es.xpt.ysf.view.search;

import java.io.IOException;

import es.xpt.ysf.logging.LogManager;
import es.xpt.ysf.view.Controller;

@SuppressWarnings("serial")
public abstract class Searchable extends Controller {
	
	private String searchString;
	
	public void dispatch ( SearchableItem si ) {
		dispatch (si, false, (String[])null);
	}
	
	public void dispatch ( SearchableItem si, boolean alternate, String... params) {
		try {
			StringBuilder sb = new StringBuilder();
			if ( params!=null ) {
				for ( String s: params ) {
					sb.append(s);
				}
			}
			super.getFacesContext().getExternalContext().dispatch(alternate?si.getAlternateView()+sb.toString():si.getResponseView()+sb.toString());
		} catch (IOException e) {
			LogManager.getLog(getClass()).error(e.getMessage(), e);
		}
		
	}
	
	public String getSearchString() {
		if ( searchString == null ) 
			searchString = readParam(); 
		return searchString;
	}
	
	public boolean isGlobalSearch() {
		if ( searchString == null ) 
			searchString = readParam();
		return searchString!=null;
	}
	
	private String readParam() {
		return super.getFacesContext().getExternalContext().getRequestParameterMap().get("globalSearch");
	}
}
